/*****************************************************************************
 *
 * MODULE:             JN-AN-1217
 *
 * COMPONENT:          app_serial_commands.c
 *
 * DESCRIPTION:        Base Device Serial Commands: Coordinator application
 *
 ****************************************************************************
 *
 * This software is owned by NXP B.V. and/or its supplier and is protected
 * under applicable copyright laws. All rights are reserved. We grant You,
 * and any third parties, a license to use this software solely and
 * exclusively on NXP products [NXP Microcontrollers such as JN5168, JN5179].
 * You, and any third parties must reproduce the copyright and warranty notice
 * and any other legend of ownership on each copy or partial copy of the
 * software.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Copyright NXP B.V. 2016. All rights reserved
 *
 ***************************************************************************/

#include <jendefs.h>
#include "dbg.h"
#include "pwrm.h"
#include "zps_gen.h"
#include "app_coordinator.h"
#include "app_zcl_task.h"
#include "app_buttons.h"
#include "app_common.h"
#include "app_serial_commands.h"
#include "app_events.h"
#include "app_main.h"
#include "ZQueue.h"
#include "ZTimer.h"

#define stricmp strcasecmp

#ifdef DEBUG_SERIAL
    #define TRACE_SERIAL      TRUE
#else
    #define TRACE_SERIAL      TRUE
#endif


#define COMMAND_BUF_SIZE   20

typedef struct
{
    uint8  au8Buffer[COMMAND_BUF_SIZE];
    uint8  u8Pos;
}tsCommand;


PRIVATE void vProcessRxChar(uint8 u8Char);
PRIVATE void vProcessCommand(void);
PRIVATE void vPrintAPSTable(void);

PRIVATE tsCommand sCommand;
char * strings[] = {
        "START UP",
        "NFN START",
        "RUNNING"
        };

/**
 * NAME: APP_taskAtSerial
 *
 * DESCRIPTION:
 *
 *
 * PARAMETERS:      Name            Usage
 *
 * RETURNS:
 * None
 */
PUBLIC void APP_taskAtSerial( void)
{
    uint8 u8RxByte;
    if (ZQ_bQueueReceive(&APP_msgSerialRx, &u8RxByte) == TRUE)
    {
        //DBG_vPrintf(TRACE_SERIAL, "Rx Char %02x\n", u8RxByte);
        vProcessRxChar(u8RxByte);
    }
}

/*
 * NAME: vProcessRxChar
 *
 * DESCRIPTION:
 * Processes the received character
 *
 * PARAMETERS:      Name            Usage
 * uint8            u8Char          Character
 *
 * RETURNS:
 * None
 */
PRIVATE void vProcessRxChar(uint8 u8Char)
{

    if ((u8Char >= 'a' && u8Char <= 'z'))
    {
        u8Char -= ('a' - 'A');
    }
    if ((sCommand.u8Pos < COMMAND_BUF_SIZE)  && (u8Char != 0x0d))
    {
        sCommand.au8Buffer[sCommand.u8Pos++] = u8Char;
    }
    else if (sCommand.u8Pos >= COMMAND_BUF_SIZE)
    {
        DBG_vPrintf(TRACE_SERIAL, "OverFlow\n");
        memset(sCommand.au8Buffer, 0, COMMAND_BUF_SIZE);
        sCommand.u8Pos = 0;
    }

    if (u8Char == 0x0d)
    {
        vProcessCommand();
    }
}

/**
 * NAME: vProcessCommand
 *
 * DESCRIPTION:
 * Processed the received command
 *
 * PARAMETERS:      Name            Usage
 *
 * RETURNS:
 * None
 */
PRIVATE void vProcessCommand(void)
{
    uint8 Delimiters[] = " ";
    uint8 *token = NULL;

//    DBG_vPrintf(TRACE_SERIAL, "Command string = '%s'\n", sCommand.au8Buffer);

    token = (uint8 *)strtok((char *)sCommand.au8Buffer, (char *)Delimiters);

//    DBG_vPrintf(TRACE_SERIAL, "Command = %s\n", token);

    APP_tsEvent sButtonEvent;
    sButtonEvent.eType = APP_E_EVENT_NONE;

    if (0 == stricmp((char*)token, "toggle"))
    {
        DBG_vPrintf(TRACE_SERIAL, "Toggle\n");
        sButtonEvent.eType = APP_E_EVENT_BUTTON_DOWN;
        sButtonEvent.uEvent.sButton.u8Button = APP_E_BUTTONS_BUTTON_SW1;
    }
    else if (0 == stricmp((char*)token, "steer"))
    {
        DBG_vPrintf(TRACE_SERIAL, "Steer\n");
        sButtonEvent.eType = APP_E_EVENT_BUTTON_DOWN;
        sButtonEvent.uEvent.sButton.u8Button = APP_E_BUTTONS_BUTTON_SW2;
    }
    else if (0 == stricmp((char*)token, "form"))
    {
        DBG_vPrintf(TRACE_SERIAL, "Form\n");
        sButtonEvent.eType = APP_E_EVENT_BUTTON_DOWN;
        sButtonEvent.uEvent.sButton.u8Button = APP_E_BUTTONS_BUTTON_1;
    }
    else if (0 == stricmp((char*)token, "find"))
    {
        DBG_vPrintf(TRACE_SERIAL, "Find\n");
        sButtonEvent.eType = APP_E_EVENT_BUTTON_DOWN;
        sButtonEvent.uEvent.sButton.u8Button = APP_E_BUTTONS_BUTTON_SW4;
    }
    else if (0 == stricmp((char*)token, "factory"))
    {
        token = (uint8 *)strtok( NULL, (char *)Delimiters);
        if (0 == stricmp((char*)token, "reset"))
        {
            DBG_vPrintf(TRACE_SERIAL, "Factory reset\n");
            APP_vFactoryResetRecords();
            vAHI_SwReset();
        }

    }
    else if (0 == stricmp((char*)token, "soft"))
    {
        token = (uint8 *)strtok( NULL, (char *)Delimiters);
        if (0 == stricmp((char*)token, "reset"))
        {
            vAHI_SwReset();
        }
    }

    else if (0 == stricmp((char*)token, "print"))
    {
        DBG_vPrintf(TRACE_SERIAL, "Key Table:\n");
        vPrintAPSTable();
    }

    if (sButtonEvent.eType != APP_E_EVENT_NONE)
    {
        ZQ_bQueueSend(&APP_msgAppEvents, &sButtonEvent);
    }

    memset(sCommand.au8Buffer, 0, COMMAND_BUF_SIZE);
    sCommand.u8Pos = 0;

}

/**
 *
 * NAME: vPrintAPSTable
 *
 * DESCRIPTION:
 * Prints the content of APS table
 *
 * RETURNS:
 * void
 *
 */
PRIVATE void vPrintAPSTable(void)
{
    uint8 i;
    uint8 j;

    ZPS_tsAplAib * tsAplAib;

    tsAplAib = ZPS_psAplAibGetAib();

    for ( i = 0 ; i < (tsAplAib->psAplDeviceKeyPairTable->u16SizeOfKeyDescriptorTable + 1) ; i++ )
    {
        DBG_vPrintf(TRUE, "%d MAC: %016llx Key: ", i, ZPS_u64NwkNibGetMappedIeeeAddr(ZPS_pvAplZdoGetNwkHandle(),tsAplAib->psAplDeviceKeyPairTable->psAplApsKeyDescriptorEntry[i].u16ExtAddrLkup));
        for(j=0; j<16;j++)
        {
            DBG_vPrintf(TRUE, "%02x ", tsAplAib->psAplDeviceKeyPairTable->psAplApsKeyDescriptorEntry[i].au8LinkKey[j]);
        }
        DBG_vPrintf(TRUE, "\n");
    }
}

